﻿/*public function createMatch():void {
			
	var match:Match = new Match;
	addChild(match);
	
	match.addEventListener(MatchEvent.INIT, matchInit);
	
	resized(null);
}

private function matchInit(event:MatchEvent):void {
	
		var player:Player	= new Player;
		player.pants.	set	= new ModelObject('model/defaultModel.a3d', 'model/int_logo_co.atf');
		event.target.scene.addPlayer(player);
		player.y = Math.random()*500;
	
	setTimeout(matchInit, 1000, event);
}*/


package game {
	import flash.system.Security;
	import flash.events.Event;
	import flash.display.Stage3D;
	import flash.display3D.Context3DRenderMode;
	import alternativa.engine3d.core.Camera3D;
	import alternativa.engine3d.core.View;
	import alternativa.engine3d.controllers.SimpleObjectController;
	import game.objects.GameObject;
	import game.match.GameScene;
	import game.match.MatchEvent;
	
	public class Match extends GameObject {
		
		public var scene:GameScene;
		private var camera:Camera3D;
		private var view:View;
		private var controller:SimpleObjectController;
		
		private var WIDTH:Number = 100;
		private var HEIGHT:Number = 100;

		public function Match():void {
			//Security.allowDomain("*");
			
			this.addEventListener(Event.ADDED_TO_STAGE, added);
		}
		
		private function added(event:Event):void {
			view = new View(WIDTH, HEIGHT, 
							config.match.view.renderToBitmap, 
							config.match.view.backgroundColor, 
							config.match.view.backgroundAlpha, 
							config.match.view.antiAlias);
			view.hideLogo();
			addChild(view);
			
			camera = new Camera3D(config.match.camera.nearClipping, config.match.camera.farClipping);
			for (var iCamera:String in config.match.camera)
				camera[iCamera] = config.match.camera[iCamera];
			
			camera.view = view;
			addChild(camera.diagram);
			
			scene = new GameScene();
			scene.addChild(camera);
			
			stage3D = stage.stage3Ds[0];
			stage3D.addEventListener(Event.CONTEXT3D_CREATE, onContext3DCreate);
			stage3D.requestContext3D(Context3DRenderMode.AUTO);
		}
		
		private function onContext3DCreate(event:Event):void {
			stage3D.removeEventListener(Event.CONTEXT3D_CREATE, onContext3DCreate);
			
			this.dispatchEvent( new MatchEvent ( MatchEvent.INIT ) );
			
			controller = new SimpleObjectController(this, camera, config.match.controller.speed, config.match.controller.speedMultiplier, config.match.controller.mouseSensitivity);
			
			stage.addEventListener(Event.ENTER_FRAME, enterFrame);
		}
		
		private function enterFrame(e:Event):void {
			//apply changes made by controller to camera
			controller.update();
			//render scene
			camera.render(stage3D);
		}
	
		public override function set width(value:Number):void {
			WIDTH = value;
			if (!view) return;
			view.width = value;
		}
		
		public override function set height(value:Number):void {
			HEIGHT = value;
			if (!view) return;
			view.height = value;
		}
	}
}